package com.hemaapp.yjnh.activity;

import java.util.ArrayList;
import java.util.List;

import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomWindowSize;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.Transformation;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.overlay.BusRouteOverlay;
import com.amap.api.maps.overlay.DrivingRouteOverlay;
import com.amap.api.maps.overlay.WalkRouteOverlay;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusStep;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveStep;
import com.amap.api.services.route.RouteBusLineItem;
import com.amap.api.services.route.RouteBusWalkItem;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkStep;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseLocation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.Route;

/**
 * 线路地图页面
 */
public class RouteMapActivity extends BaseActivity implements
		OnMarkerClickListener, OnMapLoadedListener {
	private MapView mapView;
	private ImageButton back_btn;
	private ImageButton loc_btn;
	private LinearLayout f1_lay;
	private TextView route_1;
	private TextView route_2;
	private ScrollView scrollview;
	private LinearLayout liner_lay;

	private AMap aMap;

	private Route routeExra;

	private ArrayList<String> steps = new ArrayList<String>();
	private GestureDetector mGestureDetector;
	private int scrool_max = 0;
	private boolean listup = false; // 列表已拉起
	private boolean in_animation = false;
	private int mAnimationDuration = 300;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_routemap);
		super.onCreate(savedInstanceState);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		aMap = mapView.getMap();
		aMap.setOnMarkerClickListener(this);
		aMap.setOnMapLoadedListener(this);
	}

	private void initMap() {
		if (aMap != null) {
			aMap.getUiSettings().setZoomControlsEnabled(false);
			BusPath busPath = routeExra.getBusPath();
			if (busPath != null) {
				aMap.clear();// 清理地图上的所有覆盖物
				BusRouteOverlay routeOverlay = new BusRouteOverlay(this, aMap,
						busPath, routeExra.getFromPoint(),
						routeExra.getToPoint());
				routeOverlay.removeFromMap();
				routeOverlay.addToMap();
				routeOverlay.zoomToSpan();
			}

			DrivePath drivePath = routeExra.getDrivePath();
			if (drivePath != null) {
				aMap.clear();// 清理地图上的所有覆盖物
				DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
						this, aMap, drivePath, routeExra.getFromPoint(),
						routeExra.getToPoint());
				drivingRouteOverlay.removeFromMap();
				drivingRouteOverlay.addToMap();
				drivingRouteOverlay.zoomToSpan();
			}

			WalkPath walkPath = routeExra.getWalkPath();
			if (walkPath != null) {
				aMap.clear();// 清理地图上的所有覆盖物
				WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(this,
						aMap, walkPath, routeExra.getFromPoint(),
						routeExra.getToPoint());
				walkRouteOverlay.removeFromMap();
				walkRouteOverlay.addToMap();
				walkRouteOverlay.zoomToSpan();
			}

		}
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {

	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
	}

	@Override
	protected void findView() {
		back_btn = (ImageButton) findViewById(R.id.back_btn);
		loc_btn = (ImageButton) findViewById(R.id.loc_btn);
		mapView = (MapView) findViewById(R.id.bmapView);
		f1_lay = (LinearLayout) findViewById(R.id.f1_lay);
		route_1 = (TextView) findViewById(R.id.route_1);
		route_2 = (TextView) findViewById(R.id.route_2);
		scrollview = (ScrollView) findViewById(R.id.scrollview);
		liner_lay = (LinearLayout) findViewById(R.id.liner_lay);
	}

	@Override
	protected void getExras() {
		routeExra = mIntent.getParcelableExtra("route");
	}

	@Override
	protected void setListener() {
		route_1.setText(routeExra.getDistance());
		route_2.setText(routeExra.getTime());
		back_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		loc_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// location_back();
				log_i("定位");
				aMap.setMyLocationEnabled(false);
				aMap.setMyLocationEnabled(true);
				BaseLocation.getInstance(RouteMapActivity.this).startLocation();
				double lat = Double.parseDouble(XtomSharedPreferencesUtil.get(mContext, "lat"));
				double lng = Double.parseDouble(XtomSharedPreferencesUtil.get(mContext, "lng"));
				final LatLng latLng = new LatLng(lat, lng);
				CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng,
						17);
				aMap.moveCamera(update);
				aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
			}
		});
	}

	private void initSteps() {
		BusPath busPath = routeExra.getBusPath();
		if (busPath != null) {
			List<BusStep> steps = busPath.getSteps();
			for (BusStep step : steps) {
				RouteBusLineItem item = step.getBusLine();
				RouteBusWalkItem walkItem = step.getWalk();
				if (item != null) {
					String dn = item.getDepartureBusStation()
							.getBusStationName();
					float fd = walkItem.getDistance();
					if (fd > 10) {
						String sd = BaseUtil.transDistance(fd);
						String walk = "步行" + sd + ",到达" + dn + "站";
						this.steps.add(walk);
						log_i("walk==" + walk);
					}
					String an = item.getArrivalBusStation().getBusStationName();
					int num = item.getPassStationNum() + 1;
					String busName = item.getBusLineName();
					String name = busName.split("路")[0] + "路";
					String bus = "乘坐" + name + "经过" + num + "站,到达" + an + "站下车";
					this.steps.add(bus);
					log_i("bus=" + bus);

				} else {
					float fd = walkItem.getDistance();
					String sd = BaseUtil.transDistance(fd);
					String walk = "步行" + sd + ",到达目的地";
					this.steps.add(walk);
					log_i("walk==" + walk);
				}
			}
			setLay();
		}

		DrivePath drivePath = routeExra.getDrivePath();
		if (drivePath != null) {
			List<DriveStep> steps = drivePath.getSteps();
			for (DriveStep driveStep : steps) {
				String action = driveStep.getAction();
				String i = driveStep.getInstruction();
				String drive;
				if (!isNull(action))
					drive = action + "," + i;
				else
					drive = i;
				this.steps.add(drive);
				log_i("drive=" + drive);
			}
			setLay();
		}

		WalkPath walkPath = routeExra.getWalkPath();
		if (walkPath != null) {
			List<WalkStep> steps = walkPath.getSteps();
			for (WalkStep driveStep : steps) {
				String action = driveStep.getAction();
				String i = driveStep.getInstruction();
				String walk;
				if (!isNull(action))
					walk = action + "," + i;
				else
					walk = i;
				this.steps.add(walk);
				log_i("walk=" + walk);
			}
			setLay();
		}
	}

	private void setLay() {
		liner_lay.removeAllViews();
		int screen_h = XtomWindowSize.getHeight(this);
		int max_h = (int) (screen_h * 0.3);
		int total_h = 0;
		for (String str : steps) {
			View itemview = getLayoutInflater().inflate(
					R.layout.listitem_route_2, null);
			setitemview(itemview, str);
			liner_lay.addView(itemview);
			itemview.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
			int h = itemview.getMeasuredHeight();
			total_h = total_h + h;
		}
		if (total_h < max_h) {
			scrool_max = total_h;
		} else {
			scrool_max = max_h;
		}
	}

	private void setitemview(View itemview, String str) {

		TextView txt = (TextView) itemview.findViewById(R.id.route_bus_txt);
		txt.setText(str);
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		if (marker.isInfoWindowShown()) {
			marker.hideInfoWindow();
		} else {
			marker.showInfoWindow();
		}
		return false;
	}

	@Override
	public void onMapLoaded() {
		initMap();
		initSteps();
		mGestureDetector = new GestureDetector(this, new MyOnGestureListener());
		f1_lay.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				mGestureDetector.onTouchEvent(event);
				return true;
			}
		});
	}

	/**
	 * 展开视图
	 */
	public void openStretchView() {
		scrollview.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				StretchAnimation animation = new StretchAnimation(2, scrool_max);
				animation.setDuration(mAnimationDuration);
				animation.setAnimationListener(animationListener);
				scrollview.startAnimation(animation);
				scrollview.invalidate();
			}
		});

		in_animation = true;
	}

	/**
	 * 收起视图
	 */
	public void closeStretchView() {
		scrollview.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				StretchAnimation animation = new StretchAnimation(scrool_max, 2);
				animation.setDuration(mAnimationDuration);
				animation.setAnimationListener(animationListener);
				scrollview.startAnimation(animation);
				scrollview.invalidate();
			}
		});

		in_animation = true;
	}

	private AnimationListener animationListener = new AnimationListener() {

		@Override
		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			listup = !listup;
			in_animation = false;
		}
	};

	/**
	 * 伸缩动画
	 */
	private class StretchAnimation extends Animation {
		private int startHeight;
		private int deltaHeight;

		public StretchAnimation(int startH, int endH) {
			this.startHeight = startH;
			this.deltaHeight = endH - startH;
		}

		@Override
		protected void applyTransformation(float interpolatedTime,
				Transformation t) {
			// TODO Auto-generated method stub
			if (scrollview != null) {
				LayoutParams params = (LayoutParams) scrollview
						.getLayoutParams();
				params.height = (int) (startHeight + deltaHeight
						* interpolatedTime);
				// log_w("params.height ="+ params.height);
				scrollview.setLayoutParams(params);
			}
		}
	}

	class MyOnGestureListener extends SimpleOnGestureListener {
		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			if (listup) {
				closeStretchView();
			} else {
				openStretchView();
			}
			return false;
		}

		@Override
		public void onLongPress(MotionEvent e) {
			// log_i("onLongPress-----" + getActionName(e.getAction()));
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {

			if (in_animation)
				return false;

			float deltay = e2.getY() - e1.getY();
			if (deltay < -20 && !listup) {
				openStretchView();
			} else if (deltay > 20 && listup) {
				closeStretchView();
			}
			return false;
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if (in_animation)
				return false;

			float deltay = e2.getY() - e1.getY();
			if (deltay < -20 && !listup) {
				openStretchView();
			} else if (deltay > 20 && listup) {
				closeStretchView();
			}

			return false;
		}

		@Override
		public void onShowPress(MotionEvent e) {

		}

		@Override
		public boolean onDown(MotionEvent e) {
			// log_i("onDown-----" + getActionName(e.getAction()));
			return false;
		}

		@Override
		public boolean onDoubleTap(MotionEvent e) {
			// log_i("onDoubleTap-----" + getActionName(e.getAction()));
			return false;
		}

		@Override
		public boolean onDoubleTapEvent(MotionEvent e) {
			// log_i("onDoubleTapEvent-----" + getActionName(e.getAction()));
			return false;
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			// log_i("onSingleTapConfirmed-----" +
			// getActionName(e.getAction()));
			return false;
		}
	}
}
